package com.roocon.design_pattern.chapter02_observer.demo2;

import java.util.List;

public class ThreadLifeCycleObserver implements LifeCycleListener {

  private final Object LOCK = new Object();

  public void concurrentQuery(List<String> ids) {
    if (ids != null && ids.size() > 0) {
      ids.forEach(id -> new Thread(new ObservableRunnable(this) {
        @Override public void run() {
          try {
            notifyChange(new RunnableEvent(RunnableState.RUNNING, Thread.currentThread(), null));
            System.out.println("query for the id" + id);
            Thread.sleep(1_000);
            notifyChange(new RunnableEvent(RunnableState.DONE, Thread.currentThread(), null));
          } catch (Exception e) {
            notifyChange(new RunnableEvent(RunnableState.ERROR, Thread.currentThread(), e));
          }
        }
      }).start());
    }
  }


  @Override public void onEvent(ObservableRunnable.RunnableEvent event) {
    synchronized (LOCK) {
      System.out.println("The runnable ["
          + event.getThread().getName()
          + "] data changed and state is ["
          + event.getState()
          + "]");
      if (event.getCause() != null) {
        String string =
            String.format("The runnable [%s] process failed.", event.getThread().getName());
        System.out.println(string);
        event.getCause().printStackTrace();
      }
    }
  }
}
